package com.boot.util;

import com.boot.common.entity.CustomUserDetails;
import com.boot.system.entity.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.*;

/**
 * Spring Security 工具类
 */
public class SecurityUtil {

    /**
     * 获取当前登录人信息
     *
     * @return Optional<CustomUserDetails>
     */
    private static Optional<CustomUserDetails> getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof CustomUserDetails) {
                return Optional.of((CustomUserDetails) principal);
            }
        }
        return Optional.empty();
    }

    /**
     * 获取用户账号
     *
     * @return String 用户账号
     */
    public static String getUsername() {
        return getUser().map(CustomUserDetails::getUsername).orElse(null);
    }

    /**
     * 获取用户编号
     *
     * @return Long 用户编号
     */
    public static Long getUid() {
        return getUser().map(CustomUserDetails::getId).orElse(null);
    }

    /**
     * 获取用户信息
     *
     * @return SysUser 用户信息
     */
    public static SysUser getUserInfo() {
        return getUser().map(CustomUserDetails::user).orElse(null);
    }

}
